package com.sdcs.ui;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import android.app.Activity;
import android.app.ProgressDialog;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.sdcs.R;
import com.sdcs.model.Resource;


public class ResourceActivity extends Activity {


	private Resource info ;
	
	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState); 
		setContentView(R.layout.resource_info);
		
		//获取上一个activity传过来的参数值
		info = (Resource) getIntent().getSerializableExtra("resource");

		TextView tv_name = (TextView) this.findViewById(R.id.name);
		tv_name.setText(info.getResource_name()) ;

		TextView add_date = (TextView) this.findViewById(R.id.add_date);
		add_date.setText( "发布时间: " + info.getResource_date());
		 
		TextView biaoqian = (TextView) this.findViewById(R.id.biaoqian);
		biaoqian.setText(  " 描述: " + info.getResource_describe());

		TextView btn_discuss = (TextView) findViewById(R.id.btn_discuss) ;
		btn_discuss.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {

				File sd = Environment.getExternalStorageDirectory();
				boolean can_write = sd.canWrite();
				if( can_write ){ 
					downFile( "/sdcard/" );
				}
				else{
					downFile("/data/");
				}
			}
		}) ;
	}

	private ProgressDialog dialog;
	
	public void downFile( final String filePath ) {
		dialog = new ProgressDialog(this);
		dialog.setMessage("加载中...请稍候");
		dialog.show();
		new Thread() {
			public void run() {

				String url = info.getResource_path() ;
				
				down_file(url, filePath);

				runOnUiThread(new Runnable() {
					public void run() {
						Toast.makeText( ResourceActivity.this , "下载完成，请到/data/中查看"    ,  Toast.LENGTH_LONG ).show() ;
						dialog.dismiss();
					}
				});
			};
		}.start();
	}
	
	
	public void down_file(String url, String path)  {
		
		try{
			// 获取文件名
			URL myURL = new URL(url);
			URLConnection conn = myURL.openConnection();
			conn.connect();
			InputStream is = conn.getInputStream();
			this.fileSize = conn.getContentLength();// 根据响应获取文件大小
			if (this.fileSize <= 0)
				throw new RuntimeException("无法获知文件大小 ");
			if (is == null)
				throw new RuntimeException("stream is null");
			
			File file  = new File( path );
			//如果文件夹不存在则创建  
			if( !file .exists()  && !file .isDirectory() ){     
			    System.out.println("//不存在");
			    file.mkdir();  
			} else{
			    System.out.println("//目录存在");
			}
			
			String filePath =  path +  info.getResource_name() ;
			
			FileOutputStream fos = new FileOutputStream( filePath );
			
			// 把数据存入路径+文件名
			byte buf[] = new byte[1024];
			downLoadFileSize = 0;
			do {
				// 循环读取
				int numread = is.read(buf);
				if (numread == -1) {
					break;
				}
				fos.write(buf, 0, numread);
				downLoadFileSize += numread;
	
				System.out.println( "------------------"); 
			} while (true);

			System.out.println("文件下载完成 ");
			is.close();
		} catch (Exception ex) {
			ex.printStackTrace() ;
			Log.e("tag", "error: " + ex.getMessage(), ex);
		}

	}

	ProgressBar pb;
	int fileSize;
	int downLoadFileSize;

	private Handler handler = new Handler() {
		@Override
		public void handleMessage(Message msg) {// 定义一个Handler，用于处理下载线程与UI间通讯
			if (!Thread.currentThread().isInterrupted()) {
				switch (msg.what) {
				case 0:
					pb.setMax(fileSize);
				case 1:
					pb.setProgress(downLoadFileSize);
					int result = downLoadFileSize * 100 / fileSize;
					System.out.println(result + "%"); 
					break;
				case 2:
					System.out.println("文件下载完成 "); 
					break;
				case -1:
					String error = msg.getData().getString("error");
					System.out.println("error"); 
					break;
				}
			}
			super.handleMessage(msg);
		}
	};

	
	
	
	
}
